package com.wqnmdb.im.controller.aspect;

import com.wqnmdb.im.utils.UUIDUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 自定义日志切面
 */
@Aspect
@Order(0)
@Component
public class LogAspect {
    private final static String SESSION_ID = "sessionId";

    /**
     * 自定义切点
     */
    @Pointcut("execution(* com.wqnmdb.im.controller..*.*(..))")
    public void pointCut() {
    }

    /**
     * 前置通知-记录请求信息
     *
     * @param joinPoint
     */
    @Before("pointCut()")
    public void doBeforeAdvice(JoinPoint joinPoint) {
        // MDC容器增加requestId
        MDC.put(SESSION_ID, UUIDUtil.gen());
    }

    /**
     * 后置通知-记录返回信息
     *
     * @param joinPoint
     * @param result
     */
    @AfterReturning(pointcut = "pointCut()", returning = "result")
    public void doAfterReturningAdvice(JoinPoint joinPoint, Object result) {
        MDC.remove(SESSION_ID);
    }

    /**
     * 后置异常通知-记录返回出现异
     *
     * @param joinPoint
     * @param exception
     */
    @AfterThrowing(value = "pointCut()", throwing = "exception")
    public void doAfterThrowingAdvice(JoinPoint joinPoint, Throwable exception) {
        MDC.remove(SESSION_ID);
    }

}